<template>
  <page-view>
    <!-- 头部搜索 -->
    <div class="searchTop">
      <div class="back" @click="$router.back()">
        返回
        <!-- <svg class="icon" aria-hidden="true">
          <use xlink:href="#icon-fanhui"></use>
        </svg> -->
      </div>
      <div class="search_input">
        <input
          type="text"
          :placeholder="placeholder"
          v-model.trim="keyWord"
          @keyup.enter="search"
        />
      </div>
      <div class="search" @click="search">搜索</div>
    </div>

    <!-- part1 -->
    <div class="part1" ref="part1" v-show="Show_part1_part2">
      <!-- 轮播图 -->
      <Swiper :images="images"></Swiper>

      <!-- 搜索历史 -->
      <div class="history">
        <div class="content">历史</div>
        <div class="historyList element">
          <div class="history_contain">
            <div
              class="historyItem"
              v-for="item in historyList"
              :key="item"
              @click="searchHistory(item)"
            >
              {{ item }}
            </div>
            <!-- <div>
              {{historyList}}
          </div> -->
            <!-- <div class="historyItem">nimade</div> -->
            <!-- <div class="historyItem">遍历不出来啊</div> -->
          </div>
        </div>
        <div class="clear" @click="clearLocalStorage">x</div>
      </div>
    </div>

    <!-- part2 -->
    <div class="part2 element" ref="part2" v-show="!Show_part1_part2">
      <tabs v-model:active="activeName" @click-tab="onClickTab">
        <tab title="单曲" name="singleSong" class="tabItem">
          <pull-refresh v-model="refreshing" @refresh="onRefresh">
            <list
              v-model:loading="loading"
              :finished="finished"
              finished-text="全部加载完了。。。"
              @load="onLoad"
            >
              <div
                class="singleSongItem"
                v-for="(item, index) in singleSongInfo.singleSongList"
                :key="index"
                @click="play(item, index)"
              >
                <div class="left">
                  <p class="font_two">{{ item.name }}</p>
                  <p class="font_three">
                    {{ singleSongInfo.singerNames[index] }}-{{ item.name }}
                  </p>
                </div>
                <div class="mv">
                  <svg class="icon" aria-hidden="true">
                    <use xlink:href="#icon-shipinbofang"></use>
                  </svg>
                </div>
                <div class="list" @click.stop="showActionSheet(item.id,item)">
                  <svg class="icon" aria-hidden="true">
                    <use xlink:href="#icon-liebiao-dian"></use>
                  </svg>
                </div>
              </div>
            </list>
          </pull-refresh>
        </tab>
        <tab title="歌单" name="palyList" class="tabItem">
          <pull-refresh v-model="refreshing" @refresh="onRefreshPlayList">
            <list
              v-model:loading="loading"
              :finished="finished"
              finished-text="全部加载完了。。。"
              @load="onLoadPlayList"
            >
              <div
                class="palyListItem"
                v-for="(item, index) in palyListInfo.palyList"
                :key="index"
              >
                <div class="avatar">
                  <img
                    :src="item.coverImgUrl"
                    style="width: 100%; height: 100%"
                  />
                </div>
                <div class="content">
                  <p class="overText font_two">{{ item.name }}</p>
                  <p class="font_three">
                    {{ palyListInfo.singerNames[index] }}
                  </p>
                </div>
              </div>
            </list>
          </pull-refresh>
        </tab>
        <tab title="视频" name="video" class="tabItem">内容 3</tab>
        <tab title="歌手" name="singer" class="tabItem">内容 4</tab>
      </tabs>
    </div>
  </page-view>
</template>

<script>
import Api from "../utils/api";
import {
  reactive,
  onBeforeMount,
  ref,
  toRefs,
  watch,
  onUpdated,
  onMounted,
} from "vue";
import { useRoute,useRouter } from "vue-router";
import { useStore, mapMutations } from "vuex";
import { Tab, Tabs, List, PullRefresh, Toast } from "vant";
import Swiper from "../components/Swiper.vue";
export default {
  name: "Search",
  components: {
    Swiper,
    Tab,
    Tabs,
    Toast,
    List,
    PullRefresh,
  },
  setup() {
    const router = useRouter()
    const store = useStore();
    // 是否显示加载状态
    const loading = ref(false);
    // 是否加载完成
    const finished = ref(false);
    // 下拉刷新
    const refreshing = ref(false);

    let images = reactive([
      require("../assets/image/ct.png"),
      require("../assets/image/disc_default.png"),
      require("../assets/image/needle-ab.png"),
    ]);

    let keyWord = ref("");
    let placeholder = ref("薛之谦");
    let historyListInfo = reactive({
      historyList: [],
    });
    // let historyList = reactive([]);

    let searchCategoryInfo = reactive({
      singleSongInfo: {
        singleSongList: [],
        //歌手名
        singerNames: [],
        //总页数
        pageCount: 0,
        //当前页数索引
        pageIndex: 1,
        totalCount: 0,
      },
      palyListInfo: {
        palyList: [],
        singerNames: [],
        //总页数
        pageCount: 0,
        //当前页数索引
        pageIndex: 1,
        totalCount: 0,
      },
      videoListInfo: {
        videoList: [],
        //总页数
        pageCount: 0,
        //当前页数索引
        pageIndex: 1,
        totalCount: 0,
      },
      singerListInfo: {
        singerList: [],
        //总页数
        pageCount: 0,
        //当前页数索引
        pageIndex: 1,
        totalCount: 0,
      },
    });
    //单曲
    const search = async () => {
      //1.存本地
      if (keyWord.value == "") {
        Toast.fail("搜索内容不能为空");
        return;
      }
      historyListInfo.historyList.unshift(keyWord.value);
      //历史记录去重
      historyListInfo.historyList = Array.from(
        new Set(historyListInfo.historyList)
      );
      localStorage.historyList = JSON.stringify(historyListInfo.historyList);
      console.log(localStorage.historyList);

      //2.修改显示状态
      Show_part1_part2.value = false;

      //3.获取数据
      loading.value = true;
      //参数： keywords, offset=（当前页数索引-1）*limit, type = 1, limit = 10   单曲
      //每次搜索前都要看 关键字 是否改变
      watch(keyWord, (newV, oldV) => {
        searchCategoryInfo.singleSongInfo.pageIndex = 1;
        console.log("搜索关键字，新旧值发生了改变", newV, oldV);
      });

      let results1 = await Api.Search.search(
        keyWord.value,
        (searchCategoryInfo.singleSongInfo.pageIndex - 1) * 15
      );
      //   如果页码等于1，清空食物数组
      if (searchCategoryInfo.singleSongInfo.pageIndex === 1)
        searchCategoryInfo.singleSongInfo.singleSongList.length = 0;
      console.log(results1);
      searchCategoryInfo.singleSongInfo.singleSongList.push(
        ...results1.result.songs
      );
      console.log("1122222", searchCategoryInfo.singleSongInfo.singleSongList);
      //将获取到的歌曲，提交到仓库进行替换
      store.commit(
        "setPlayList",
        searchCategoryInfo.singleSongInfo.singleSongList
      );

      searchCategoryInfo.singleSongInfo.totalCount = results1.result.songCount;
      searchCategoryInfo.singleSongInfo.pageCount = parseInt(
        results1.result.songCount / 15
      );
      //处理歌手信息
      searchCategoryInfo.singleSongInfo.singerNames = [];
      // singerNames=['薛之谦/张靓颖','']
      results1.result.songs.forEach((item, index, _arr) => {
        let str = "";
        item.ar.forEach((item2, index2, _arr2) => {
          if (index2 == item.ar.length - 1) {
            str += item2.name;
          } else {
            str += item2.name + "/";
          }
        });
        searchCategoryInfo.singleSongInfo.singerNames.push(str);
      });

      console.log("保存后的结果", searchCategoryInfo.singleSongInfo);
      loading.value = false;
      finished.value =
        searchCategoryInfo.singleSongInfo.pageIndex >=
        searchCategoryInfo.singleSongInfo.pageCount;
      refreshing.value = false;
    };

    //歌单
    const search1 = async () => {
      //1.存本地
      if (keyWord.value == "") {
        Toast.fail("搜索内容不能为空");
        return;
      }
      historyListInfo.historyList.unshift(keyWord.value);
      //历史记录去重
      historyListInfo.historyList = Array.from(
        new Set(historyListInfo.historyList)
      );
      localStorage.historyList = JSON.stringify(historyListInfo.historyList);
      console.log(localStorage.historyList);

      //2.修改显示状态
      Show_part1_part2.value = false;

      //3.获取数据
      loading.value = true;
      //参数： keywords, offset=（当前页数索引-1）*limit, type = 1, limit = 10   单曲
      //每次搜索前都要看 关键字 是否改变
      watch(keyWord, (newV, oldV) => {
        searchCategoryInfo.palyListInfo.pageIndex = 1;
        console.log("搜索关键字，新旧值发生了改变", newV, oldV);
      });

      let results = await Api.Search.search(
        keyWord.value,
        (searchCategoryInfo.palyListInfo.pageIndex - 1) * 15,
        1000
      );
      console.log(results);
      // //   如果页码等于1，清空食物数组
      if (searchCategoryInfo.palyListInfo.pageIndex === 1)
        searchCategoryInfo.palyListInfo.palyList.length = 0;
      console.log(results);
      searchCategoryInfo.palyListInfo.palyList.push(
        ...results.result.playlists
      );

      searchCategoryInfo.palyListInfo.totalCount = results.result.playlistCount;
      searchCategoryInfo.palyListInfo.pageCount = parseInt(
        results.result.playlistCount / 15
      );
      //处理歌手信息
      searchCategoryInfo.palyListInfo.singerNames = [];
      // singerNames=['薛之谦/张靓颖','']
      results.result.playlists.forEach((item, index, _arr) => {
        let str = "";
        let numObj = item.playCount / 10000;
        let count = numObj.toFixed(1);
        str +=
          item.trackCount +
          "首,by " +
          item.creator.nickname +
          ",播放 " +
          count +
          " 万次";
        searchCategoryInfo.palyListInfo.singerNames.push(str);
      });

      console.log("保存后的结果", searchCategoryInfo.palyListInfo);
      loading.value = false;
      finished.value =
        searchCategoryInfo.palyListInfo.pageIndex >=
        searchCategoryInfo.palyListInfo.pageCount;
      refreshing.value = false;
    };

    onBeforeMount(() => {
      historyListInfo.historyList = localStorage.historyList
        ? JSON.parse(localStorage.historyList)
        : [];
    });

    //点击搜索后，显示第二个部分
    let Show_part1_part2 = ref(true);

    const activeName = ref("singleSong");

    //点击清空历史记录
    const clearLocalStorage = () => {
      localStorage.clear();
    };

    // 单曲 下滚懒加载菜单
    const onLoad = () => {
      console.log(111);
      if (
        searchCategoryInfo.singleSongInfo.pageIndex <
        searchCategoryInfo.singleSongInfo.pageCount
      ) {
        console.log(222);
        searchCategoryInfo.singleSongInfo.pageIndex += 1;
        search(
          keyWord.value,
          (searchCategoryInfo.singleSongInfo.pageIndex - 1) * 15
        );
      }
    };
    // 单曲 下拉刷新菜单
    const onRefresh = () => {
      finished.value = false;
      refreshing.value = true;
      searchCategoryInfo.singleSongInfo.singleSongList.length = 0;
      search(
        keyWord.value,
        (searchCategoryInfo.singleSongInfo.pageIndex - 1) * 15
      );
    };

    // 歌单 下滚懒加载菜单
    const onLoadPlayList = () => {
      console.log(111);
      if (
        searchCategoryInfo.palyListInfo.pageIndex <
        searchCategoryInfo.palyListInfo.pageCount
      ) {
        console.log(222);
        searchCategoryInfo.palyListInfo.pageIndex += 1;
        search1();
      }
    };
    // 歌单 下拉刷新菜单
    const onRefreshPlayList = () => {
      finished.value = false;
      refreshing.value = true;
      searchCategoryInfo.palyListInfo.palyList.length = 0;
      search1();
    };

    //历史记录搜索
    const searchHistory = (item) => {
      keyWord.value = item;
      search(
        keyWord.value,
        (searchCategoryInfo.singleSongInfo.pageIndex - 1) * 15
      );
    };

    const onClickTab = ({ title }) => {
      Toast(title);
      //切换过来就要去获取数据了
      if (title == "单曲") {
        search();
      } else if (title == "歌单") {
        search1();
      } else if (title == "视频") {
      } else if (title == "歌手") {
      }
    };

    //单机拉起
    function showActionSheet(id,item) {
      console.log('点我知道是哪首歌的id',id);
      store.commit("showActionSheet", {
        list: ["下一首播放", "收藏到歌单", "下载", "评论", "分享"],
        success: function (index) {
          if (index == 0) {
            console.log("下一首播放");
          } else if (index == 1) {
            console.log("收藏到歌单");
          } else if (index == 2) {
            console.log("下载");
          } else if (index == 3) {
            router.push({name:'comment',query:{id:id,name:item.name,picUrl:item.al.picUrl,author:item.ar[0].name}})
            console.log("评论");
          } else if (index == 4) {
            console.log("分享");
          }
        },
      });
    }

    const play = (item, index) => {
      store.commit("setPlayIndex", index);
      console.log(index);
      //只需要传一个index即可，仓库可以拿到具体的歌
      router.push({ name: "songPlayDetail", query: { index_current: index } });
    };
    return {
      images,
      search,
      keyWord,
      placeholder,
      ...toRefs(historyListInfo),
      Show_part1_part2,
      activeName,
      ...toRefs(searchCategoryInfo),
      clearLocalStorage,
      refreshing,
      loading,
      finished,
      onRefresh,
      onLoad,
      searchHistory,
      onClickTab,
      search1,
      onLoadPlayList,
      onRefreshPlayList,
      showActionSheet,
      play,
    };
  },
};
</script>

<style lang="less" scoped>
.searchTop {
  height: 50px;
  width: 6.5rem;
  margin: 15px auto;
  // background-color: yellow;
  text-align: center;
  display: flex;
  line-height: 50px;
  justify-content: space-between;
  & > div {
    height: 100%;
    // border: 1px solid black;
  }
  .back {
    width: 15%;
  }
  .search_input {
    width: 65%;
    input {
      border-radius: 40px;
      padding-left: 40px;
      width: 100%;
      height: 100%;
    }
  }
  .search {
    width: 15%;
  }
}
.history {
  width: 6.5rem;
  height: 36px;
  line-height: 36px;
  margin: auto;
  // background-color: skyblue;
  display: flex;
  text-align: center;
  & > div {
    height: 100%;
    // border: 1px solid black;
  }
  .content {
    width: 10%;
  }
  .historyList {
    width: 80%;
    overflow: auto;
    .history_contain {
      white-space: nowrap;
      height: 100%;
      .historyItem {
        width: fit-content;
        display: inline-block;
        height: 100%;
        margin: 0 5px;
        background-color: #eee;
        border-radius: 30px;
        padding: 0 20px;
        // border: 1px solid black;
      }
    }
  }

  .clear {
    width: 10%;
  }
}

.part2 {
  width: 6.5rem;
  height: 543px;
  margin: auto;
  overflow: auto;
  .tabItem {
    height: 543px;
    // background-color: orange;
  }
  .singleSongItem {
    box-sizing: content-box;
    padding: 10px 0px;
    // margin: 5px 0;
    width: 100%;
    // background-color: yellow;
    // height: 50px;
    display: flex;
    & > div {
      // border: 1px solid black;
      height: 100%;
    }
    .left {
      width: 70%;
    }
    .mv {
      width: 15%;
    }
    .list {
      width: 15%;
    }
  }

  .palyListItem {
    box-sizing: content-box;
    padding: 10px 0px;
    // margin: 5px 0;
    width: 100%;
    // background-color: yellow;
    height: 50px;
    // border: 1px solid black;
    display: flex;
    align-items: center;
    .avatar {
      width: 50px;
      height: 50px;
    }
    .content {
      margin-left: 10px;
      flex: 1;
    }
  }
}
</style>